import React, { useEffect, useState } from 'react'
import style from './goods.module.css'
import { Button, Checkbox, Select } from 'antd'
import { getGuoGoodsData } from '../../request'
import { message, Popconfirm } from 'antd';
interface GoodsType {
    key: string;
    shopname: string;
    title: string;
    date: string;
    address: number;
    money: string;
    goodsmoney: string;
    type: string;
    typex: string;
    butype: string;
    image: string;
}
function Index() {
    const [goodsData, setGoodsData] = useState<GoodsType[]>([])
    const [loadingMore, setLoadingMore] = useState(false)
    // 全选反选
    const [isAllSelected, setIsAllSelected] = useState(false)
    const [selectedGoods, setSelectGoods] = useState<boolean[]>([])
    // 搜索
    const [searchKeyword, setSearchKeyword] = useState('');
    const [category, setCategory] = useState('全部');
    const [subCategory, setSubCategory] = useState('全部');
    const [exposureType, setExposureType] = useState('全部');
    const [goodnessSetting, setGoodnessSetting] = useState('好货');
    const [refundType, setRefundType] = useState('微信');
    const [shopNameInput, setShopNameInput] = useState('');
    // 搜索
    const handleSearch = async () => {
        const res = await getGuoGoodsData();
        const initialData = res.data.tabs;
        const filteredData = initialData.filter(item => {
            const titleMatches = !searchKeyword || item.title.toLowerCase().includes(searchKeyword.toLowerCase());
            const categoryMatches = category === '全部' || item.typex === category;
            const subCategoryMatches = subCategory === '全部' || item.butype === subCategory;
            const exposureMatches = exposureType === '全部' || item.type === exposureType;
            const goodnessMatches = goodnessSetting === '好货' || item.butype === goodnessSetting;
            const refundMatches = refundType === '微信' || item.butype === refundType;
            const shopNameMatches = !shopNameInput || item.shopname.toLowerCase().includes(shopNameInput.toLowerCase());
            return titleMatches && categoryMatches && subCategoryMatches && exposureMatches && goodnessMatches && refundMatches && shopNameMatches;
        });
        setGoodsData(filteredData);
        setSelectGoods(new Array(filteredData.length).fill(false));
    };
    useEffect(() => {
        getGuoGoodsData().then(res => {
            setGoodsData(res.data.tabs)
        });
    }, []);
    const handleSelectAll = () => {
        const newSelectedGoods = goodsData.map(() => true)
        setIsAllSelected(true)
        setSelectGoods(newSelectedGoods)
    }
    const handleSetAllAsGood = async () => {
        if (isAllSelected) {
            // 如果全选状态，将所有商品设为好货
            const updatedGoodsData = goodsData.map(item => ({
                ...item,
                type: '推荐'
            }));
            setGoodsData(updatedGoodsData);
            // 更新选中状态数组
            setSelectGoods(updatedGoodsData.map(() => true));
        } else {
            // 如果不是全选状态，只将选中的商品设为好货
            const updatedGoodsData = goodsData.map((item, index) => {
                if (selectedGoods[index]) {
                    return {
                        ...item,
                        type: '推荐'
                    };
                }
                return item;
            });
            setGoodsData(updatedGoodsData);
            // 更新选中状态数组
            setSelectGoods(updatedGoodsData.map(item => item.type === '推荐'));
        }
    };
    const handleSelectInverse = () => {
        const newSelectedGoods = selectedGoods.map((selected) => !selected)
        setIsAllSelected(newSelectedGoods.every((selected) => selected))
        setSelectGoods(newSelectedGoods)
    }
    const handleCheckChange = (index: number) => {
        const newSelectedGoods = [...selectedGoods]
        newSelectedGoods[index] = !newSelectedGoods[index]
        const allSelected = newSelectedGoods.every((selected) => selected)
        setIsAllSelected(allSelected)
        setSelectGoods(newSelectedGoods)

    }
    // 触底加载更多
    const handleScroll = () => {
        const scrollTop = window.scrollY//当前滚动的距离
        const windowHeight = window.innerHeight//窗口的高度
        const documentHeight = document.documentElement.scrollHeight//表格的高度

        if (scrollTop + windowHeight >= documentHeight - 50 && !loadingMore) {
            setLoadingMore(true)
            loadingMoreGoods()
        }
    }
    const loadingMoreGoods = async () => {
        try {
            const res = await getGuoGoodsData()
            setGoodsData((prevData) => [...prevData, ...res.data.tabs])
        } catch (error) {
            console.error('请求数据错误：', error)
        } finally {
            setLoadingMore(false)
        }
    }
    useEffect(() => {
        window.addEventListener('scroll', handleScroll)
        return () => {
            window.removeEventListener('scroll', handleScroll)
        }
    }, [loadingMore])

    // 设为好货
    const handleSetting = async (index: number) => {
        // 创建一个新的商品数据副本
        const updateGoodsData = [...goodsData]
        // 更新对呀的商品标签为‘推荐’
        updateGoodsData[index] = {
            ...updateGoodsData[index],
            type: '推荐'
        }
        // 更新商品数据
        setGoodsData(updateGoodsData)
    }
    // 删除
    const confirm = (index: number) => {
        console.log(index);
        const updatedGoodsData = goodsData.filter((_, i) => i !== index)
        setGoodsData(updatedGoodsData)
        message.success('Click on Yes');
    };

    const cancel = () => {
        console.log();
        message.error('Click on No');
    };
    // 清空筛选
    const clearFilters = () => {
        setSearchKeyword('');
        setCategory('全部');
        setSubCategory('全部');
        setExposureType('全部');
        setGoodnessSetting('好货');
        setRefundType('微信');
        setShopNameInput('');
        // 可以根据实际需求，决定是否重置全选和选中商品状态
        // 如果需要重置全选和选中商品状态，可以添加以下代码
        setIsAllSelected(false);
        setSelectGoods([]);
    };
    return (
        <div className={style.goodsMain}>
            <div className={style.goodsList}>
                <h3>商品管理</h3>
                <div style={{ display: 'flex', justifyContent: 'space-between', width: 900, marginTop: '20px' }}>
                    <p>
                        商品大类：
                        <Select
                            style={{ width: 230 }}
                            placeholder='请选择大类'
                            options={
                                [
                                    { value: '全部', label: '全部' },
                                    { value: '电商', label: '电商' },
                                    { value: '海报', label: '海报' },
                                    { value: '小红书', label: '小红书' },
                                ]
                            }
                            onChange={(value) => setCategory(value)}
                        ></Select>
                    </p>
                    <p>
                        商品小类：
                        <Select
                            style={{ width: 240 }}
                            placeholder='请选择小类'
                            options={
                                [
                                    { value: '全部', label: '全部' },
                                    { value: '热门', label: '热门' },
                                    { value: '上传', label: '上传' },
                                    { value: '自主', label: '自主' },
                                ]
                            }
                            onChange={(value) => setSubCategory(value)}
                        ></Select>
                    </p>
                    <p>
                        曝光类型：
                        <Select
                            style={{ width: 100 }}
                            defaultValue='全部'
                            options={
                                [
                                    { value: '全部', label: '全部' },
                                    { value: '上架', label: '上架' },
                                    { value: '下架', label: '下架' },
                                ]
                            }
                            onChange={(value) => setExposureType(value)}
                        ></Select>
                    </p>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', width: 670, marginTop: '20px' }}>
                    <p>
                        好货设置：
                        <Select
                            style={{ width: 100, marginRight: '10px' }}
                            defaultValue='好货'
                            options={
                                [
                                    { value: '好货', label: '好货' },
                                    { value: '好货绝佳', label: '好货绝佳' },
                                    { value: '好货一般', label: '好货一般' },
                                    { value: '中等货', label: '中等货' },
                                ]
                            }
                            onChange={(value) => setGoodnessSetting(value)}
                        ></Select>
                        <Select
                            style={{ width: 100 }}
                            defaultValue='所有分组'
                            options={
                                [
                                    { value: '所有分组', label: '所有分组' },
                                    { value: '好货绝佳', label: '好货绝佳' },
                                    { value: '好货一般', label: '好货一般' },
                                    { value: '中等货', label: '中等货' },
                                ]
                            }
                        ></Select>
                    </p>
                    <p>
                        退款类型：
                        <Select
                            style={{ width: 240 }}
                            placeholder='请选择退款类型'
                            options={
                                [
                                    { value: '微信', label: '微信' },
                                    { value: 'QQ', label: 'QQ' },
                                    { value: '支付宝', label: '支付宝' },
                                    { value: '平台', label: '平台' },
                                ]
                            }
                            onChange={(value) => setRefundType(value)}
                        ></Select>
                    </p>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', width: 670, marginTop: '20px' }}>
                    <div style={{ display: 'flex', height: '32px' }}>
                        <p>店铺名称：</p>
                        <input style={{ borderRadius: '5px', border: '1px #ccc solid', width: 240 }} type="text" placeholder='请输入店铺名称' onChange={(e) => setShopNameInput(e.target.value)} />
                    </div>
                    <div style={{ display: 'flex', height: '32px' }}>
                        <p>商品名称：</p>
                        <input style={{ borderRadius: '5px', border: '1px #ccc solid', width: 240 }} type="text" placeholder='请输入商品名称' onChange={(e) => setSearchKeyword(e.target.value)} />
                    </div>
                </div>
                <div style={{ marginTop: '20px' }}>
                    <Button type='primary' style={{ marginRight: '10px' }} onClick={handleSearch}>搜索</Button>
                    <Button style={{ marginRight: '10px' }} onClick={clearFilters}>清空筛选条件</Button>
                    <Button style={{ marginRight: '10px' }}>设置模版</Button>
                </div>
            </div>
            <div className={style.goodsTable}>
                <div style={{ background: '#f7f9fc', height: 35, lineHeight: '35px' }}>
                    &emsp;
                    <Checkbox checked={isAllSelected}
                        onChange={() => {
                            if (isAllSelected) {
                                handleSelectInverse()
                            } else {
                                handleSelectAll()
                            }
                        }}
                    />&emsp;全选&emsp; <Button size='small' onClick={handleSetAllAsGood}>批量设为好货</Button>
                </div>
                <div className={style.goodsDiv}>
                    <div className={style.goodsDiv_top}>
                        <p>&emsp;&emsp;&emsp;</p>
                        <p className={style.p1}>商品描述</p>
                        <p className={style.p2}>价格</p>
                        <p className={style.p3}>销量</p>
                        <p className={style.p4}>店铺</p>
                        <p className={style.p5}>创建时间</p>
                        <p className={style.p6}>操作</p>
                    </div>
                    {
                        goodsData.map((item, index) => (
                            <div className={`${style.goodsDiv_body} ${item.butype === '下架' ? style.greyedOut : ''}`} key={index}>
                                &emsp;<Checkbox
                                    checked={selectedGoods[index]}
                                    onChange={() => handleCheckChange(index)}
                                />&emsp;
                                <div style={{ display: 'flex', width: 500 }} >
                                    <p> <img src={item.image} alt="" /></p>
                                    <p>
                                        <span>{item.title}</span>
                                        <span>产地：{item.address} &emsp;特性：<b style={{ border: '1px solid red', color: 'red' }}>{item.type}</b></span><br />
                                        <span>大类：{item.typex}</span>
                                    </p>
                                </div>
                                <p style={{ width: 120, textAlign: 'center' }}>￥{item.money}</p>
                                <p style={{ width: 120, textAlign: 'center' }}>{item.goodsmoney}</p>
                                <p style={{ width: 120, textAlign: 'center' }}>{item.shopname}</p>
                                <p style={{ width: 160, textAlign: 'center' }}>{item.date}</p>
                                <div style={{ width: 150, marginLeft: '30px', textAlign: 'center' }}>
                                    {/* 设为好货 */}
                                    <p><a onClick={() => handleSetting(index)}>设为好货</a></p>
                                    <p><a>{item.butype}</a></p>
                                    <p><Popconfirm
                                        title="删除这条商品"
                                        description="你确定要删除这个商品吗?"
                                        onConfirm={() => confirm(index)}
                                        onCancel={cancel}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <a>删除</a>
                                    </Popconfirm></p>
                                </div>
                            </div>
                        ))
                    }

                </div>

            </div>
        </div>
    )
}

export default Index
